#ifndef _CAPP_H_
    #define _CAPP_H_

#include "CApp.h"
#include "CAppStateManager.h"
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_net.h>

#define FPS 1000/30 //1 segundo / 30 frames

using namespace std;
unsigned int timer = 0;

int main(int argc, char* argv[]) {
	CApp theApp;
	return theApp.onExecute();
}

CApp::CApp(){
	surfDisplay = NULL;
	running = true;
}
/**
 * Loop central do jogo.
 * Trata os eventos, modifica elementos da tela e carrega.
 */
int CApp::onExecute(){
		if(!onInit()){
			return -1;
		}
		timer = SDL_GetTicks();
		CAppStateManager::setActiveAppState(APPSTATE_INTRO, NULL);
		SDL_Event event;
	int i = 0;
	while (running) {

		//controlar o fps do jogo.
		if (SDL_GetTicks() - timer > FPS) {
			timer = SDL_GetTicks();
			while (SDL_PollEvent(&event)) {
				onEvent(&event);
			}
			onRender();
			onLoop();
			onRender();
		}
	}
		onCleanUp();
		return 0;
	}
/**
 * Inicializa os componentes da SDL
 */
bool CApp::onInit() {
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
		std::cout << "SDL_Init: " << SDL_GetError() << std::endl;
		return false;
	}

	if ((surfDisplay = SDL_SetVideoMode(800, 600, 32,
			SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL) {
		std::cout << "Create Display: " << std::endl;
		return false;
	}

	SDL_WM_SetCaption("Forca Online v0.5", NULL);

	if(TTF_Init() < 0){
		std::cout << "Iniciar a TTF " << std::endl;
		return false;
	}

	if(SDLNet_Init() < 0){
		std::cout << "SDLNet_Init: " << SDLNet_GetError() << std::endl;
		return false;
	}

	return true;
}

void CApp::onEvent(SDL_Event* event){
	CEvent::onEvent(event);
	CAppStateManager::onEvent(event);

}

void CApp::onExit(){
	running = false;
	SDLNet_Quit();
}

void CApp::onLoop() {

    CAppStateManager::onLoop();
}

void CApp::onRender(){
	CAppStateManager::onRender(surfDisplay);
	SDL_Flip(surfDisplay);
}

void CApp::onCleanUp(){
    CAppStateManager::setActiveAppState(APPSTATE_NONE, NULL);
    TTF_Quit();
    SDL_FreeSurface(surfDisplay);
    SDL_Quit();
}

#endif
